package com.service.websocket.Interceptor;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.common.utils.constant.Constants;
import com.common.utils.tool.UserUtil;
import com.service.websocket.handler.MessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author xianggj
 * @description: websocket拦截器
 * @date 2019/8/20 16:33
 */
@Component
@Slf4j
public class WebSocketInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler handler, Map<String, Object> map) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
            ServletServerHttpResponse serverHttpResponse = (ServletServerHttpResponse) response;
            HttpServletRequest servletRequest = serverHttpRequest.getServletRequest();
            //获取用户 需要创建链接的时候将用户发送到session里面
            String userId = MDC.get(Constants.USER_ID);
            String uuid = IdUtil.simpleUUID();
            if (userId != null){
                map.put(MessageHandler.USER_ID, userId);
                map.put(MessageHandler.USER_NAME, UserUtil.get(userId));
                map.put(MessageHandler.WINDOW_ID, uuid);

                //获取当前请求地址
                String header = servletRequest.getScheme() + "://" +
                        servletRequest.getServerName() + ":" + servletRequest.getServerPort() +
                        servletRequest.getContextPath();
                map.put(MessageHandler.HEADER, header);
                //如果有业务id 创建链接时就需要添加业务id 如任务id
                String busId = servletRequest
                        .getParameter(MessageHandler.BUS_ID);
                if (StrUtil.isNotBlank(busId)){
                    map.put(MessageHandler.BUS_ID, busId);
                }
                //如果有业务id 创建链接时就需要添加业务id 如任务id
                String token = servletRequest
                        .getParameter(MessageHandler.TOKEN);
                if (StrUtil.isNotBlank(token)){
                    map.put(MessageHandler.TOKEN, token);
                }
                log.info("连接信息如下：");
                log.info("-|连接用户ID为"+userId);
                log.info("-|连接窗口ID为"+uuid);
                Cookie cookie = new Cookie(MessageHandler.WINDOW_ID, uuid);
                cookie.setPath("/");
                serverHttpResponse.getServletResponse().addCookie(cookie);
            } else {
                log.error("获取登录用户失败,请登录后重试");
                return true;
            }
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest,
                               ServerHttpResponse serverHttpResponse,
                               WebSocketHandler webSocketHandler, Exception e) {
        if (e != null){
            e.printStackTrace();
        }
    }
}
